//
//  controllerWithTab.m
//  ElektroM
//
//  Created by Michael on 09.10.09.
//  Copyright 2009 Artgruppe inc. All rights reserved.
//

#import "controllerWithTab.h"
#include "graph.h"
#import "Constants.h"

#import "undergroundController.h"
#import "busController.h"
#import "MainViewController.h"

//#import "AppDelegate.h"
controllerWithTab* busContr=nil;
controllerWithTab* undergContr=nil;
controllerWithTab* mainController=nil;	

Graph* graph=NULL;
/*
@interface controllerWithTab(C_Plus_p)

-(void) setGraph:(Graph*)gr;

@end

@implementation controllerWithTab(C_Plus_p)
// for using only one instance of graph-object in all needed interfaces:
-(void) setGraph:(Graph*)gr
{
	graph=gr;
}

@end
*/
@implementation controllerWithTab
@synthesize tabBarController;
//@synthesize _firstView;

-(void) setGraph:(void*) p
{
	graph=(Graph*)p;
}

-(void*) getGraph
{
	return (void*)graph;
}

// reload the view manually, after we changed the tab item:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
	//_nCurrentTab=item.tag;
	_nCurrentTab=tabBarController.selectedIndex;
	//printf("Tab changed:%d\n", _nCurrentTab);
	// reload our view
	//[self loadAccordingToTab:_nCurrentTab];	
}

-(void)storageSetSelectedStations:(int)whichOne TheStationValue:(int)nStation FromController:(NSString*)sName
{
	int nIndex=[_directions indexOfObject:sName];
	//printf("Set Which: %d; nStation: %d\n", whichOne, nStation);
	//printf("Found index: %d Count:%d\n", nIndex, [_directions count]);
	switch (whichOne) {
		case 1:
			anStationsStart[nIndex]=nStation;			
			break;
		case 2:
			anStationsEnd[nIndex]=nStation;			
			break;
		case 3:
			_uStations[0]=nStation;
			break;
		case 4:
			_uStations[1]=nStation;
			break;
		case 5:
			_bUndergroundUpperToolbarShown=nStation==1?true:false;
			break;
	}	
	//printf("set UStation %d, %d\n", _uStations[0], _uStations[1]);
}

-(NSInteger)storageGetSelectedStations:(int)whichOne FromController:(NSString*)sName
{
	int nIndex=[_directions indexOfObject:sName];
	//printf("Get Which: %d\n", whichOne);
	//printf("Found index: %d Count:%d\n", nIndex, [_directions count]);
	//printf("Get UStation %d, %d\n", _uStations[0], _uStations[1]);
	switch (whichOne) {
		case 1:
			return anStationsStart[nIndex];
		case 2:
			return anStationsEnd[nIndex];	
		case 3:
			return _uStations[0];
		case 4:
			return _uStations[1];
		case 5:
			return _bUndergroundUpperToolbarShown;			
	}	
	return -1;
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}


-(void)setMaster:(controllerWithTab*)yourMaster
{
	master=yourMaster;
}

-(void)initStorage
{
	_nCurrentTab=0;
	// init arrays:
	anStationsStart=(NSInteger*)malloc(sizeof(NSInteger)*CountOfDirections);
	memset(anStationsStart, -1, sizeof(NSInteger)*CountOfDirections);
	anStationsEnd=(NSInteger*)malloc(sizeof(NSInteger)*CountOfDirections);
	memset(anStationsEnd, -1, sizeof(NSInteger)*CountOfDirections);
	_uStations=(NSInteger*)malloc(sizeof(NSInteger)*2);
	memset(anStationsEnd, -1, sizeof(NSInteger)*2);
	_bUndergroundUpperToolbarShown=false;
}

// used for setting needed (loaded from disk) data for Underground view
-(void)starageSetPointersStatStart:(NSInteger*)StationsStart 
				   withStationsEnd:(NSInteger*)StationsEnd 
					 withUStations:(NSInteger*)UStations
{
	anStationsStart=StationsStart;
	anStationsEnd=StationsEnd;
	_uStations=UStations;
}

-(void)readStorage
{
	// get remembered user selection (current tab);
	NSString *filePath = [self dataFilePath];		
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        _nCurrentTab = [((NSString*)[array objectAtIndex:0]) integerValue];
		//printf("Selected tab: %d\n", _nCurrentTab);
		for(int i=0; i<CountOfDirections; i++){
			anStationsStart[i]=[((NSString*)[array objectAtIndex:i*2+1]) integerValue];
			anStationsEnd[i]=[((NSString*)[array objectAtIndex:i*2+2]) integerValue];
			//printf("Start:%d Stop: %d\n", anStationsStart[i], anStationsEnd[i]);
		}
		// read info about our 2 stations in Underground-view:
		for(int i=0; i<2; i++)
			_uStations[i]=[((NSString*)[array objectAtIndex:i+CountOfDirections*2+1]) integerValue];
		
        //printf("Reading UStations: %d %d\n", _uStations[0], _uStations[1]);		
		_bUndergroundUpperToolbarShown=[((NSString*)[array objectAtIndex:CountOfDirections*2+1+2]) integerValue]==1?true:false;
		//printf("Data was read completely! Panel: %d\n", [((NSString*)[array objectAtIndex:CountOfDirections*2+1+2]) integerValue]);
		[array release];
    }
	else{
		_nCurrentTab=0; 
		//printf("Path doesn't exist!");
	}	
}

-(void)writeStorage
{
	// save the tab position first:
	_nCurrentTab=tabBarController.selectedIndex;
	NSMutableArray *array = [[NSMutableArray alloc] init];    
	NSString* num=[NSString stringWithFormat:@"%d", _nCurrentTab];	
	[array addObject:num];
	// next write info about last user's selections:
	
	for(int i=0; i<CountOfDirections; i++){
		[array addObject:[NSString stringWithFormat:@"%d", anStationsStart[i]]];
		[array addObject:[NSString stringWithFormat:@"%d", anStationsEnd[i]]];
	}
	//printf("Writing UStations: %d %d\n", _uStations[0], _uStations[1]);
	// write info about our 2 stations in Underground-view:
	for(int i=0; i<2; i++)
		[array addObject:[NSString stringWithFormat:@"%d", _uStations[i]]];		
	
	// write states:
	/*
	printf("String of underground status: %s\n", 
		   [[NSString stringWithFormat:@"%d", _bUndergroundUpperToolbarShown?1:0] UTF8String]);
	 */
	[array addObject: [NSString stringWithFormat:@"%d", _bUndergroundUpperToolbarShown?1:0]];
	
    [array writeToFile:[self dataFilePath] atomically:YES];
    [array release];	
}

-(void)releaseStorage
{
	free(anStationsEnd);
	free(anStationsStart);
	free(_uStations);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
